package com.weilele.mvvmlib.model

import com.weilele.base.library.BaseViewModel
import com.weilele.mvvm.base.helper.PageHelper
import com.weilele.mvvm.base.helper.pageHelperData
import com.weilele.mvvm.base.helper.updatePageHelper
import com.weilele.mvvm.base.livedata.data
import com.weilele.mvvm.base.livedata.isRunning
import com.weilele.mvvm.utils.net.awaitHttp
import com.weilele.mvvm.utils.net.createRetrofitApi
import kotlinx.coroutines.Dispatchers
import retrofit2.http.GET
import retrofit2.http.Path

interface PicApi {
    //https://gank.io/api/v2/data/category/Girl/type/Girl/page/1/count/10
    companion object {
        val self by lazy {
            createRetrofitApi<PicApi>("https://gank.io/")
        }
    }

    @GET("api/v2/data/category/Girl/type/Girl/page/{pageIndex}/count/{pageNum}")
    suspend fun getMeizi(
        @Path("pageIndex") pageIndex: Int,
        @Path("pageNum") pageNum: Int,
    ): PicBean
}

class PicViewModel : BaseViewModel() {

    val picPageData = pageHelperData<PicBean.DataDTO>()

    /**
     * 加载数据
     */
    fun getPic(isRefresh: Boolean) {
        val pageHelper = picPageData.data
        if (pageHelper != null) {
            //不是第一次请求数据
            if (!pageHelper.hasNextPage) {
                return
            }
        }
        if (picPageData.isRunning) {
            return
        }
        val pageIndex = if (isRefresh) {
            1
        } else {
            (pageHelper?.currentPageIndex ?: 1) + 1
        }
        picPageData.runInCoroutineScope(runIfSuccess = true, context = Dispatchers.Default) {
            val result = PicApi.self.getMeizi(pageIndex, 6)
//            val url = "https://gank.io/api/v2/data/category/Girl/type/Girl/page/$pageIndex/count/6"
//            val result = url.awaitHttp<PicBean>()
            picPageData.updatePageHelper(
                pageIndex,
                result.data,
                isRefresh,
                checkHasNextPage(picPageData.data, result),
                result
            )
        }
    }

    private fun checkHasNextPage(
        data: PageHelper<PicBean.DataDTO, Any>?,
        result: PicBean
    ): Boolean {
        var count = 0
        data?.eachPageList { _, value ->
            count += (value?.count() ?: 0)
        }
        count += (result.data?.count() ?: 0)
        return count < result.totalCounts
    }
}